package com.solarsmile.gallery.adapter

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.*
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.solarsmile.gallery.model.PhotoItem
import com.solarsmile.gallery.R
import com.solarsmile.gallery.viewmodel.DATA_STATUS_LOAD_MORE
import com.solarsmile.gallery.viewmodel.DATA_STATUS_NO_MORE
import com.solarsmile.gallery.viewmodel.GalleryViewModel
import com.solarsmile.gallery.viewmodel.NET_WORK_ERROR
import kotlinx.android.synthetic.main.gallery_footer.view.*
import kotlinx.android.synthetic.main.gallery_item.view.*

class GalleryAdapter(val galleryViewModel: GalleryViewModel) : ListAdapter<PhotoItem, MyViewHolder>(
    DIFFCALLBACK
) {
    companion object {
        const val NOMARL_VIEW_TYPE = 0
        const val FOOTER_VIEW_TYPE = 1
    }

    var footViewStatus = DATA_STATUS_LOAD_MORE

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val holder: MyViewHolder
        if (viewType == NOMARL_VIEW_TYPE) {
            holder = MyViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.gallery_item,
                    parent,
                    false
                )
            )
            holder.itemView.setOnClickListener {
                Bundle().apply {
                    //       废弃
//                putParcelable("Photo", getItem(holder.adapterPosition))  //将点击到的数据提交到二级页面
//                holder.itemView.findNavController().navigate(R.id.action_galleryFragment_to_photoFragment,this)  //this指代创建的Bundle
                    putParcelableArrayList(
                        "PHOTO_LIST",
                        ArrayList(currentList)
                    )  //currentList是adpater的属性，但此处类型不匹配，将currentList放入ArrayList()中后即可
                    putInt("PHOTO_POSITION", holder.adapterPosition)  //将点击的图片的序号传到二级页面
                    holder.itemView.findNavController()
                        .navigate(R.id.action_galleryFragment_to_pagerPhotoFragment, this)
                }
            }
        } else {
            holder = MyViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.gallery_footer,
                    parent,
                    false
                ).also {
                    (it.layoutParams as StaggeredGridLayoutManager.LayoutParams).isFullSpan = true
                    it.setOnClickListener {itemView ->
                        itemView.progressBar.visibility = View.VISIBLE
                        itemView.textView.text = "正在加载"
                        galleryViewModel.fetchData()
                    }
                }
            )
        }
        return holder
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) FOOTER_VIEW_TYPE else NOMARL_VIEW_TYPE
    }

    override fun getItemCount(): Int {
        return super.getItemCount() + 1 //  +1 是增加的最底部的Footer
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if (position == itemCount - 1) {
            with(holder.itemView) {
                when (footViewStatus) {
                    DATA_STATUS_LOAD_MORE -> {
                        isClickable = false
                        progressBar.visibility = View.VISIBLE
                        textView.text = resources.getString(R.string.loading)
                    }
                    DATA_STATUS_NO_MORE -> {
                        isClickable = false
                        progressBar.visibility = View.GONE
                        textView.text = resources.getString(R.string.noloading)
                    }
                    NET_WORK_ERROR -> {
                        isClickable = false
                        progressBar.visibility = View.GONE
                        textView.text = resources.getString(R.string.neterror)
                    }
                }
            }
            return
        }
        val photoItem: PhotoItem = getItem(position)
        with(holder.itemView) {
            shimmer_item.apply {
                setShimmerColor(0x50EDEDED)
                setShimmerAngle(0)
                startShimmerAnimation()
            }
            textView_photoowner.text = photoItem.photoOwner
            textView_thumbup.text = photoItem.photoLikes.toString()
            textView_heart.text = photoItem.photoFavorites.toString()
        }
//        holder.itemView.shimmer_item.apply {
//            setShimmerColor(0x50EDEDED)
//            setShimmerAngle(0)
//            startShimmerAnimation()
//        }
//        holder.itemView.textView_photoowner.text = getItem(position).photoOwner
//        holder.itemView.textView_thumpup.text = getItem(position).photoLikes.toString()
//        holder.itemView.textView_heart.text = getItem(position).photoFavorites.toString()
        Glide.with(holder.itemView)
            .load(getItem(position).previewUrl)
            .placeholder(R.drawable.ic_insert_photo)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also {
                        //判空避免空指针
                        holder.itemView.shimmer_item?.stopShimmerAnimation()
                    }
                }
            }).into(holder.itemView.imageView_item)
    }

    object DIFFCALLBACK : DiffUtil.ItemCallback<PhotoItem>() {
        override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem.photoId == newItem.photoId
        }

        override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem == newItem
        }
    }
}

class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

}